const { ethers, upgrades } = require("hardhat");

async function main() {
    console.log("🚀 开始部署NFT拍卖市场...");

    // 获取部署者账户
    const [deployer] = await ethers.getSigners();
    console.log("部署者地址:", deployer.address);
    console.log("部署者余额:", ethers.utils.formatEther(await deployer.getBalance()), "ETH");

    // Sepolia测试网的Chainlink价格feed地址
    const SEPOLIA_ETH_USD_FEED = "0x694AA1769357215DE4FAC081bf1f309aDC325306";
    const SEPOLIA_CCIP_ROUTER = "0x0BF3dE8c5D3e8A2B34D2BEeB17ABfCeBaf363A59";

    try {
        // 1. 部署价格预言机合约
        console.log("\n📊 部署价格预言机合约...");
        const PriceOracle = await ethers.getContractFactory("PriceOracle");
        const priceOracle = await upgrades.deployProxy(
            PriceOracle,
            [SEPOLIA_ETH_USD_FEED],
            { initializer: 'initialize' }
        );
        await priceOracle.deployed();
        console.log("✅ PriceOracle 部署完成:", priceOracle.address);

        // 2. 部署NFT合约
        console.log("\n🎨 部署NFT合约...");
        const AuctionNFT = await ethers.getContractFactory("AuctionNFT");
        const auctionNFT = await upgrades.deployProxy(
            AuctionNFT,
            [
                "拍卖市场NFT",           // name
                "ANFT",                 // symbol
                deployer.address,       // royalty receiver
                250,                    // 2.5% royalty
                ethers.utils.parseEther("0.01"), // mint price
                10000                   // max supply
            ],
            { initializer: 'initialize' }
        );
        await auctionNFT.deployed();
        console.log("✅ AuctionNFT 部署完成:", auctionNFT.address);

        // 3. 部署拍卖工厂合约
        console.log("\n🏭 部署拍卖工厂合约...");
        const AuctionFactory = await ethers.getContractFactory("AuctionFactory");
        const auctionFactory = await upgrades.deployProxy(
            AuctionFactory,
            [
                priceOracle.address,    // price oracle
                deployer.address        // fee receiver
            ],
            { initializer: 'initialize' }
        );
        await auctionFactory.deployed();
        console.log("✅ AuctionFactory 部署完成:", auctionFactory.address);

        // 4. 部署跨链拍卖合约
        console.log("\n🌉 部署跨链拍卖合约...");
        const CrossChainAuction = await ethers.getContractFactory("CrossChainAuction");
        const crossChainAuction = await CrossChainAuction.deploy(
            SEPOLIA_CCIP_ROUTER,
            priceOracle.address
        );
        await crossChainAuction.deployed();
        console.log("✅ CrossChainAuction 部署完成:", crossChainAuction.address);

        // 5. 配置合约关系
        console.log("\n⚙️ 配置合约关系...");

        // 设置NFT合约的拍卖市场地址
        await auctionNFT.setAuctionMarket(auctionFactory.address);
        console.log("✅ NFT合约已配置拍卖市场地址");

        // 等待交易确认
        console.log("\n⏳ 等待交易确认...");
        await new Promise(resolve => setTimeout(resolve, 10000));

        // 6. 验证部署
        console.log("\n🔍 验证合约部署...");

        const oracleOwner = await priceOracle.owner();
        const nftName = await auctionNFT.name();
        const factoryOwner = await auctionFactory.owner();

        console.log("价格预言机所有者:", oracleOwner);
        console.log("NFT名称:", nftName);
        console.log("工厂合约所有者:", factoryOwner);

        // 7. 铸造测试NFT
        console.log("\n🎨 铸造测试NFT...");
        const mintTx = await auctionNFT.mintNFT(
            deployer.address,
            "ipfs://QmTestNFTMetadataHash",
            { value: ethers.utils.parseEther("0.01") }
        );
        await mintTx.wait();
        console.log("✅ 测试NFT铸造完成");

        // 8. 输出部署信息
        console.log("\n" + "=".repeat(60));
        console.log("🎉 NFT拍卖市场部署完成!");
        console.log("=".repeat(60));
        console.log("📊 PriceOracle:", priceOracle.address);
        console.log("🎨 AuctionNFT:", auctionNFT.address);
        console.log("🏭 AuctionFactory:", auctionFactory.address);
        console.log("🌉 CrossChainAuction:", crossChainAuction.address);
        console.log("=".repeat(60));

        // 9. 生成使用示例
        console.log("\n📝 使用示例:");
        console.log("1. 授权NFT给工厂合约:");
        console.log(`   auctionNFT.setApprovalForAll("${auctionFactory.address}", true)`);
        console.log("\n2. 创建拍卖:");
        console.log(`   auctionFactory.createAuction(`);
        console.log(`     "${auctionNFT.address}",  // NFT合约`);
        console.log(`     1,                        // Token ID`);
        console.log(`     "${ethers.utils.parseEther("0.1")}", // 起拍价`);
        console.log(`     "${ethers.utils.parseEther("0.2")}", // 保留价`);
        console.log(`     86400                     // 1天时长`);
        console.log(`   )`);

        // 10. 保存部署信息
        const deploymentInfo = {
            network: "sepolia",
            timestamp: new Date().toISOString(),
            deployer: deployer.address,
            contracts: {
                PriceOracle: priceOracle.address,
                AuctionNFT: auctionNFT.address,
                AuctionFactory: auctionFactory.address,
                CrossChainAuction: crossChainAuction.address
            },
            chainlinkFeeds: {
                ETH_USD: SEPOLIA_ETH_USD_FEED,
                CCIP_Router: SEPOLIA_CCIP_ROUTER
            }
        };

        const fs = require('fs');
        fs.writeFileSync(
            'deployment-info.json',
            JSON.stringify(deploymentInfo, null, 2)
        );
        console.log("\n💾 部署信息已保存到 deployment-info.json");

        // 11. 生成Etherscan链接
        console.log("\n🔗 Etherscan链接:");
        console.log(`PriceOracle: https://sepolia.etherscan.io/address/${priceOracle.address}`);
        console.log(`AuctionNFT: https://sepolia.etherscan.io/address/${auctionNFT.address}`);
        console.log(`AuctionFactory: https://sepolia.etherscan.io/address/${auctionFactory.address}`);
        console.log(`CrossChainAuction: https://sepolia.etherscan.io/address/${crossChainAuction.address}`);

    } catch (error) {
        console.error("\n❌ 部署失败:", error);
        process.exit(1);
    }
}

main()
    .then(() => {
        console.log("\n🎊 部署完成!");
        process.exit(0);
    })
    .catch((error) => {
        console.error("❌ 部署脚本执行失败:", error);
        process.exit(1);
    });
